import React, { Component } from "react";
import { connect } from "dva";
import { formatMessage, FormattedMessage, setLocale } from "umi-plugin-react/locale";
import Link from "umi/link";
import { Checkbox, Alert, Icon, Input, Tabs, Form, Button, notification, Modal } from "antd";
import Login from "@/components/Login";
import styles from "./Login.less";
import CryptoJS from "crypto-js";
import qywxLogo from "@/assets/qywx.png";
import lockPng from "@/assets/lock.png";
import banner from "@/assets/loginBanner.png";
import { getSystemPlatformInfo } from "@/services/platformManagement";
import jsonDataUtils from "@/utils/jsonDataUtils";
import MultiUserSelection from "./MultiUserSelection";
import { routerRedux } from "dva/router";
import ywzd from "@/assets/ywzd.png";
import ywzdlogo from "@/assets/ywzdlogo.png";
import SelectLang from "@/components/SelectLang"
const { TabPane } = Tabs;
const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;
const isShowVerificationCode = true; //是否显示验证码

@connect(({ login, loading }) => ({
	login,
	submitting: loading.effects["login/login"],
}))
class LoginPage extends Component {
	state = {
		type: "account",
		autoLogin: true,
		randomNum: null,
		codeNum: "",
		isSaveLogin: false,
		activeKey: 1,
		loading: true,
		isShowQywxLogin: 2,
		// isShowQywxLogin: 4,
		platformInfo: {},
    showPart:"",
    tenantList:[],
    resendCountdown: 0,
    countdownInterval: null,
    showSmsModal: false, // 控制弹窗显示状态
    smsCodeInput: "" // 短信验证码输入值
	};

	componentDidMount() {
		const { location: { query } } = this.props;
		if (isShowVerificationCode) {
			this.getRandomNumber(8);
		};
		if (query.code) {
			this.loginByQywx(query.code);
		};
		this.getPlatformInfo();
    if(query.param){
      this.setState({
        showPart:"sso"
      },() => {
        this.ssoLogin(query.param)
      })
    }else{
      this.setState({
        showPart:'login'
      })
    }
	}

  componentWillUnmount() {
    clearInterval(this.state.countdownInterval);
  }

	getPlatformInfo = async () => {
		const res = await getSystemPlatformInfo();
		this.setState({ platformInfo: res })
	}

	loginByQywx = (code) => {
		const { dispatch } = this.props;
		dispatch({
			type: "login/loginByQywx",
			payload: { code },
		});
	};

	getRandomNumber = (n) => {
		let num = "";
		for (let i = 0; i < n; i++) {
			num += Math.floor(Math.random() * 10);
		};
		this.setState({ randomNum: num });
	};

	onTabChange = (type) => {
		this.setState({ type });
	};

	onGetCaptcha = () =>
		new Promise((resolve, reject) => {
			this.loginForm.validateFields(["mobile"], {}, (err, values) => {
				if (err) {
					reject(err);
				} else {
					const { dispatch } = this.props;
					dispatch({ type: "login/getCaptcha", payload: values.mobile, }).then(resolve).catch(reject);
				}
			});
		});

  handleSubmit = (values) => {
    const { randomNum, isSaveLogin, showPart } = this.state;
    let obj = values;
    obj.key = randomNum;
    obj.code = parseInt(values.code);
    obj.isSaveLogin = isSaveLogin;
    obj.type = showPart == "login" ? "password" : "code"
    const { dispatch,history } = this.props;
    const encryptParam = this.encrypt(JSON.stringify(values));
    dispatch({
      type: "login/login",
      payload: { data: encryptParam },
      callback: (res) => {
        this.getRandomNumber(8);
        console.log('登录的回调===',res);
        if(res.code != -1){
          if(res && res.length){
            if(res.length == 1){
              //只有一个租户 判断权限后直接进入
              if(!res[0].validity){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountExpired' }))
                return false
              }
              if(res[0].status != 0){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountDisabled' }))
                return false
              }
              if(res[0].tenantBanned == 1){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.tenantDisabled' }))
                return false
              }
              this.toLoginItem(res[0])
            }else{
              dispatch(routerRedux.push({ pathname:"/user/userSelect", param: { tenantList: res } }));
            }
          }else{
            this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountPasswordError' }))
          }
        }

      },
    });
	};

	changeAutoLogin = (e) => {
		this.setState({ autoLogin: e.target.checked });
	};

	renderMessage = (content) => (
		<Alert style={{ marginBottom: 24 }} message={content} type='error' showIcon />
	);

	changeCodeNum = (e) => {
		this.setState({ codeNum: e.target.value });
	};

	changeImage = () => {
		this.getRandomNumber(8);
	};

	changeIsSaveLogin = (e) => {
		this.setState({ isSaveLogin: e.target.checked });
	};

	encrypt(encryptString) {
		var PUBLIC_KEY = "biaopin123456789";
		var key = CryptoJS.enc.Utf8.parse(PUBLIC_KEY);
		var srcs = CryptoJS.enc.Utf8.parse(encryptString);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7,
		});
		return encrypted.toString();
	}

	handleTabsChange = (key) => {
		// console.log(key);
		this.setState({ activeKey: key }, () => {
			if (key == 2) {
				this.appendJs();
			}
		});
	};

	appendJs = () => {
		const script = document.createElement("script");
		script.src = "http://wwcdn.weixin.qq.com/node/wework/wwopen/js/wwLogin-1.2.4.js";
		document.body.appendChild(script);

		setTimeout(function () {
			const url = window.location.href;
			const redirect_url = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${window.appid}&agentid=${window.agentid}&redirect_uri=${url}&state=STATE`;
			let wwLogin = new WwLogin({
				id: "wx_reg", // 登录页面显示二维码的容器id
				appid: window.appid, // 企业微信的CorpID，在企业微信管理端查看
				agentid: window.agentid, // 授权方的网页应用id，在具体的网页应用中查看
				redirect_uri: encodeURIComponent(url), // 重定向的地址，需要进行encode
				state: new Date().getTime(),
				href: "", // 自定义样式链接，只支持https协议的资源地址
			});
		}, 500);
	};

	regSubmit = () => {
		this.props.form.validateFields((err, values) => {
			if (!err) {
				// console.log('-----------------', values);
			}
		})
	}

  toLoginItem = data => {
    const locale = data.language
    if (locale) {
      setLocale(locale, false)
    }
    const { dispatch } = this.props;
    dispatch({
      type: "login/loginToTenant",
      payload: {
        id:data.id,
        username:data.name,
        tenantId:data.tenantId,
        type:data.type,
        path:data.path,
        nick:data.nick,
        isAdmin:data.isAdmin,
        applicationId:data.applicationId,
        language: data.language,
        mobilePhone: data.mobilePhone
      },
      callback: (res) => {
        console.log('选择租户后的回调',res);

      },
    });
  }

  ssoLogin = param => {
    const { dispatch } = this.props;
    dispatch({
      type: "login/loginBySSO",
      payload: { param },
      callback: (res) => {
        console.log('sso的回调===',res);
        if(res.code != -1){
          if(res && res.length){
            if(res.length == 1){
              //只有一个租户 判断权限后直接进入
              if(!res[0].validity){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountExpired' }))
                return false
              }
              if(res[0].status != 0){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountDisabled' }))
                return false
              }
              if(res[0].tenantBanned == 1){
                this.showErrorNotification(formatMessage({ id: 'login.checkbox.tenantDisabled' }))
                return false
              }
              this.toLoginItem(res[0])
            }else{
              dispatch(routerRedux.push({ pathname:"/user/userSelect", param: { tenantList: res } }));
            }
          }else{
            this.showErrorNotification(formatMessage({ id: 'login.checkbox.accountPasswordError' }))
          }
        }
      },
    });
  }

  doValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error && values.agree){
        this.handleSubmit(values)
      }
    })
  }

  forgetPassword = () => {
	  this.props.history.push("/user/resetPassword");
  }

  showErrorNotification = (message) =>{
    notification.error({
      message:message,
      key:"errorMessage"
    })
  }

  showSuccessNotification = (message) => {
    notification.success({
      message: message,
      key: "successMessage"
    });
  };

  // 显示短信验证码弹窗
  showSmsModal = () => {
    const { getFieldValue } = this.props.form;
    const mobile = getFieldValue('username');

    // 校验手机号是否填写
    if (!mobile) {
      this.showErrorNotification(formatMessage({ id: 'login.checkbox.inputPhoneNumber' }));
      return;
    }

    // 使用正则表达式校验是否为大陆手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(mobile)) {
      this.showErrorNotification(formatMessage({ id: 'login.validation.validPhone' }));
      return;
    }

    this.setState({ showSmsModal: true });
  };

  // 处理短信验证码输入变化
  handleSmsCodeInputChange = (e) => {
    // 获取输入框的值
    const value = e.target.value;
    // 更新 state 中的 smsCodeInput
    this.setState({ smsCodeInput: value });
  };

  // 处理短信验证码弹窗提交
  handleSmsModalSubmit = () => {
    const { smsCodeInput, randomNum } = this.state;
    const { getFieldValue } = this.props.form;
    const mobile = getFieldValue('username');

    // 调用发送短信验证码的接口
    const { dispatch } = this.props;
    dispatch({
      type: "login/getSmsCaptcha",
      payload: { phone:mobile, key: randomNum, code: smsCodeInput },
      callback: (res) => {
        this.getRandomNumber(8);
        if (res.code != -1) {
          this.showSuccessNotification(formatMessage({ id: 'login.checkbox.smsCodeSuccess' }));
          // 关闭弹窗，发送短信验证码按钮开始倒计时
          const countdownInterval = setInterval(() => {
            const resendCountdown = this.state.resendCountdown - 1;
            if (resendCountdown === 0) {
              clearInterval(this.state.countdownInterval);
              this.setState({
                countdownInterval: null
              });
            }
            this.setState({
              resendCountdown
            });
          }, 1000)
          this.setState({
            countdownInterval,
            resendCountdown: 60,
            showSmsModal: false
          });
        }
      }
    });
  };

  render() {
    const { login, submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      type,
      autoLogin,
      randomNum,
      isSaveLogin,
      activeKey,
      loading,
      isShowQywxLogin,
      platformInfo,
      showPart,
      tenantList,
      resendCountdown,
      showSmsModal,
      smsCodeInput
    } = this.state;

    return (
      showPart === 'sso' ? (
        <div></div>
      ) : showPart === 'login' ? (
        <div className={styles.outBoxContainer} style={{ position: "relative", paddingBottom: 85 }}>
          <div style={{ textAlign: "center" }}>
            <img src={ywzd} style={{ height: 80, marginBottom: 20 }} />
            <div className={styles.loginContainer} style={{position:"relative"}}>
				<div style={{position:"absolute",top:10,right:10,zIndex:9999}}>
					<SelectLang />
				</div>
              <div className={styles.loginTitle}>{formatMessage({ id: 'login.title.main' })}</div>
              <Form>
                <Form.Item>
                  {getFieldDecorator("username",{rules:[
                    {
                      required: true,
                      message: formatMessage({ id: "login.validation.usernameRequired", }),
                    },
                  ]})(
                    <Input placeholder={formatMessage({ id: 'login.placeholder.account', })} prefix={<img src="../../../newUI/login-user.png" style={{width:20}} />} />
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator("password",{rules:[
                    {
                      required: true,
                      message: formatMessage({ id: "login.validation.passwordRequired", }),
                    },
                  ]})(
                    <Input.Password placeholder={formatMessage({ id: 'login.placeholder.password', })} onPressEnter={(e) => this.doValidate()} prefix={<img src="../../../newUI/login-lock.png" style={{width:20}} />}  />
                  )}
                </Form.Item>
                <Form.Item>
                  <div style={{ display: "flex",gap:16 }}>
                    <Form.Item style={{marginBottom:0}}>
                      {getFieldDecorator("code",{rules:[
                        {
                          required: true,
                          message: formatMessage({ id: 'login.placeholder.verificationCode', }),
                        },
                      ]})(
                        <Input
                          placeholder={formatMessage({ id: 'login.placeholder.verificationCode', })}
                          onChange={this.changeCodeNum}
                          type={"number"}
                          maxLength={3}
                        />
                      )}
                    </Form.Item>
                    {randomNum ? (
                      <img
                        src={"/cloud/number.jpg?key=" + randomNum}
                        style={{
                          width: 126,
                          cursor: "pointer",
                          height: 40,
                          flexShrink:0
                        }}
                        onClick={this.changeImage}
                      />
                    ) : (
                      ""
                    )}
                  </div>
                </Form.Item>
                <Form.Item style={{marginBottom:12}}>
                  {getFieldDecorator("agree",{rules:[
                    {
                      required: true,
                      message: formatMessage({ id: 'login.checkbox.pleaseCheck' }),
                    },
                  ]})(
					<div style={{display:'block',width:'320px'}}>
                    <Checkbox>
                      {formatMessage({ id: 'login.agree' })}
                      <a href="/custom/userAgreement" target="_blank" >
                        {formatMessage({ id: 'login.agreement.user' })}
                      </a>
                      {formatMessage({ id: 'login.agree.and' })}
                      <a href="/custom/privacypolicy" target="_blank">
                        {formatMessage({ id: 'login.agreement.privacy' })}
                      </a>
                    </Checkbox>
					</div>
                  )}
                </Form.Item>
                <Button type="primary" block style={{background:"#0052CC"}} onClick={this.doValidate}>
                  {formatMessage({ id: 'login.button.login' })}
                </Button>
                <Button style={{ float: "left", padding: "0px" }} type="link" onClick={this.forgetPassword}>{formatMessage({ id: 'login.link.forgotPassword' })}</Button>
                <Button style={{ float: "left", padding: "0px" }} type="link" onClick={() => this.setState({ showPart: 'phoneLogin' })}>{formatMessage({ id: 'login.checkbox.mobileVerificationLogin' })}</Button>
              </Form>
            </div>
          </div>

          <div style={{position:"absolute",bottom:10,left:"50%",transform:"translateX(-50%)",textAlign:"center"}}>
            <img src={ywzdlogo} style={{width:110}} />
            <div style={{color:"#0070C0",fontSize:"26px",letterSpacing:"13px",fontWeight:"bold",textAlign:"center",paddingLeft:13}}>AIOS</div>
          </div>
        </div>
      ) : showPart === 'phoneLogin' ? (
        <div className={styles.outBoxContainer}>
          <div  style={{ position: "relative", paddingBottom: 85 }}>
            <div style={{ textAlign: "center" }}>
              <img src={ywzd} style={{ height: 80, marginBottom: 20 }} />
              <div className={styles.loginContainer}>
                <div className={styles.loginTitle}>{formatMessage({ id: 'login.title.main' })}</div>
                <Form>
                  <Form.Item>
                    {getFieldDecorator("username", {
                      rules: [
                        {
                          required: true,
                          message: formatMessage({ id: "validation.phone-number.required", }),
                        },
                      ]
                    })(
                      <Input placeholder={formatMessage({ id: 'login.checkbox.inputPhoneNumber', })} prefix={<img src="../../../newUI/login-user.png" style={{ width: 20 }} />} />
                    )}
                  </Form.Item>
                  <Form.Item>
                    <div style={{ display: "flex", gap: 16 }}>
                      {getFieldDecorator("code",{rules:[
                        {
                          required: true,
                          message: formatMessage({ id: 'login.checkbox.inputSmsCode', }),
                        },
                      ]})(
                        <Input
                          placeholder={formatMessage({ id: 'login.checkbox.inputSmsCode', })}
                          style={{ flex: 1 }}
                        />
                      )}
                      <Button
                        type="primary"
                        disabled={resendCountdown > 0}
                        onClick={this.showSmsModal}
                        style={{ width: 126, flexShrink: 0, background: resendCountdown > 0 ? '#ddd' : '#0052CC' }}
                      >
                        {resendCountdown > 0 ? `${resendCountdown}s` : formatMessage({ id: 'login.checkbox.sendSmsCode' })}
                      </Button>
                    </div>
                  </Form.Item>
                  <Form.Item style={{ marginBottom: 12 }}>
                    {getFieldDecorator("agree", {
                      rules: [
                        {
                          required: true,
                          message: formatMessage({ id: 'login.checkbox.pleaseCheck' }),
                        },
                      ]
                    })(
                      <Checkbox>
                        {formatMessage({ id: 'login.agree' })}
                        <a href="/custom/userAgreement" target="_blank" >
                          {formatMessage({ id: 'login.agreement.user' })}
                        </a>
                        {formatMessage({ id: 'login.agree.and' })}
                        <a href="/custom/privacypolicy" target="_blank">
                          {formatMessage({ id: 'login.agreement.privacy' })}
                        </a>
                      </Checkbox>
                    )}
                  </Form.Item>
                  <Button type="primary" block style={{ background: "#0052CC" }} onClick={this.doValidate}>
                    {formatMessage({ id: 'login.button.login' })}
                  </Button>
                  <Button style={{ float: "left", padding: "0px" }} type="link" onClick={this.forgetPassword}>
                    {formatMessage({ id: 'login.link.forgotPassword' })}
                  </Button>
                  <Button style={{ float: "left", padding: "0px" }} type="link" onClick={() => this.setState({ showPart: 'login' })}>
                    {formatMessage({ id: 'login.link.passwordLogin' })}
                  </Button>
                </Form>
              </div>
            </div>

            <div style={{ position: "absolute", bottom: 10, left: "50%", transform: "translateX(-50%)", textAlign: "center" }}>
              <img src={ywzdlogo} style={{ width: 110 }} />
              <div style={{ color: "#0070C0", fontSize: "26px", letterSpacing: "13px", fontWeight: "bold", textAlign: "center", paddingLeft: 13 }}>AIOS</div>
            </div>
          </div>
          <Modal
            title={formatMessage({ id: 'login.checkbox.inputTextCode' })}
            centered
            visible={showSmsModal}
            onCancel={() => this.setState({ showSmsModal: false })}
            footer={null}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <Input
                placeholder={formatMessage({ id: 'login.placeholder.verificationCode' })}
                value={smsCodeInput}
                onChange={this.handleSmsCodeInputChange}
                style={{ flex: 1 }}
              />
              {randomNum ? (
                <img
                  src={"/cloud/number.jpg?key=" + randomNum}
                  style={{ width: 126, cursor: "pointer", height: 40 }}
                  onClick={this.changeImage}
                />
              ) : (
                ""
              )}
            </div>
            <Button
              type="primary"
              onClick={this.handleSmsModalSubmit}
              style={{ marginTop: 16, width: "100%", background: "#0052CC" }}
            >
              {formatMessage({ id: 'login.button.submit' })}
            </Button>
          </Modal>
        </div>
      ) : (
        <div></div>
      )
		);

}
}

export default Form.create()(LoginPage);
